/**
 * Copyright 2008-2009 HAN.BIFANG
 *
 *  Licensed under the Apache License, Version 2.0 (the "License");
 *  you may not use this file except in compliance with the License.
 *  You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 *  Unless required by applicable law or agreed to in writing, software
 *  distributed under the License is distributed on an "AS IS" BASIS,
 *  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 *  See the License for the specific language governing permissions and
 *  limitations under the License.
 *
 */
package han.bashe.business.ejb;

import han.bashe.common.cache.InnerCache;
import han.bashe.common.util.CommonUtils;

import javax.ejb.ActivationConfigProperty;
import javax.ejb.MessageDriven;
import javax.jms.Message;
import javax.jms.MessageListener;
import javax.jms.TextMessage;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;

import v1.sync.web.bifang.han.SyncRequestDocument;
import v1.sync.web.bifang.han.SyncRequestDocument.SyncRequest.Clear;

/**
 * @Author kent
 */
@MessageDriven
(mappedName = "han.bashe.sync.Topic",
    name = "SyncMDB",
    activationConfig = {
    @ActivationConfigProperty(propertyName = "destinationType", propertyValue = "javax.jms.Topic")
        }
)
public class SyncMDB implements MessageListener{
	private static Log log = LogFactory.getLog(SyncMDB.class);
	
	public void onMessage(Message msg) {
		try {
			TextMessage m = (TextMessage)msg;
			log.info("recieving sync request " + m.getText());
			SyncRequestDocument doc = SyncRequestDocument.Factory.parse(m.getText());
			if(! doc.validate()){
				log.error("request xml format error :" + m.getText());
				return;
			}
			if(doc.getSyncRequest().getClearAll() != null){
				InnerCache.removeAll();
			}else{
				Clear cl = doc.getSyncRequest().getClear();
				if(cl.getType().intValue() == Clear.Type.INT_SERVICE_BUS){
					if(CommonUtils.isEmpty(cl.getKey())){
						InnerCache.removeAllBus();
					}else{
						InnerCache.removeServiceBus(cl.getKey());
					}
				}else if(cl.getType().intValue() == Clear.Type.INT_SERVICE){
					if(CommonUtils.isEmpty(cl.getKey())){
						InnerCache.removeAllServices();
					}else{
						InnerCache.removeService(cl.getKey());
					}
				}else if(cl.getType().intValue() == Clear.Type.INT_MAPPING_SERVICE){
					if(CommonUtils.isEmpty(cl.getKey())){
						InnerCache.removeAllServices();
					}else{
						InnerCache.removeMappingService(cl.getKey());
					}
				}else if(cl.getType().intValue() == Clear.Type.INT_SECURITY){
					InnerCache.removeAllSecurity();
				}
			}
			
		} catch (Exception e) {
			log.error("error",e);
		}
		
		
		
	}

}
